<?php
/*
 * @author eBIZ Team <dev@jungo.com.cn>
 * @copyright  Copyright (c) , ShenZhen JunGO Technology Co., Ltd. All rights reserved.
 * @license  Commercial authorization, unauthorized use and modification are prohibited
 * @url www.jungo.com.cn
 */

namespace ckeeper\http;



use Admin\System\Consts;
use Resource\DynamicForm\DynamicForm;
use Resource\DynamicForm\FormAbstract;
use Selibra\Di\Annotations\Autowired;
use Selibra\Di\Annotations\Component;
use Selibra\Di\DI;
use Selibra\Http\Annotations\Controller;
use Selibra\Http\Annotations\Route;
use Selibra\Http\Route\RouterConfig;
use Selibra\Model\EntityProxy;
use ckeeper\db\Transaction;
use Selibra\Tools\Console;
use ckeeper\entity\ConfigEntity;
use ckeeper\services\ConfigService;

/**
 * 系统配置
 * Class Setting
 * @package Admin\System\Controller
 */
#[Component]
#[Controller("/system/configs", Setting::class)]
class Setting extends http
{

    /**
     * @var ConfigService
     */
    #[Autowired]
    protected ConfigService $configService;


    #[Route("/", RouterConfig::REQUEST_GET)]
    public function index()
    {
        $configList = [];
        $topGroups = $this->configService->selectGroups();
        foreach ($topGroups as $key => $topGroup) {
            // 转数组
            $topGroupArray = EntityProxy::entityConversionToArray($topGroup);
            // 获取子组
            $childGroups = $this->configService->selectGroups($topGroup->getKey());
            if (!empty($childGroups)) {
                foreach ($childGroups as $childGroup) {
                    // 获取配置
                    $childGroupArray = EntityProxy::entityConversionToArray($childGroup);
                    $configs = $this->configService->selectConfigsByGroupKey($childGroup->getKey());
                    $childGroupArray['configs'] = $this->configsToFormsData($configs);
                    $topGroupArray['childGroups'][] = $childGroupArray;
                }
            } else {
                // 获取配置
                $configs = $this->configService->selectConfigsByGroupKey($topGroup->getKey());
                $topGroupArray['configs'] = $this->configsToFormsData($configs);
            }
            $configList[] = $topGroupArray;
        }

        return $this->success("获取成功", [
            'configList' => $configList
        ]);
    }


    /**
     * @param array $configs
     * @return array
     */
    private function configsToFormsData(array $configs)
    {
        if (empty($configs)) {
            return [];
        }
        /** @var DynamicForm $dynamicForm */
        $dynamicForm = DI::getObjectContext(DynamicForm::class);
        $values = [];
        $this->configService::configEntitiesToForms($configs, function (ConfigEntity $configEntity, FormAbstract $form) use ($dynamicForm, &$values) {
            $form->setSubTitle("({$configEntity->getKey()})");
            $dynamicForm->addForm($form);
            if (in_array($configEntity->getKey(), Consts::ConfigArr)) {
                $value = implode("\n", array_filter(explode(",", $configEntity->getValue())));
                $configEntity->setValue($value);
            }
            $values[$configEntity->getKey()] = $configEntity->getValue();
        });
        $dynamicForm->setValues($values);
        return $dynamicForm->getFormsData();
    }

    /**
     * 保存系统配置
     */
    #[Route('/', RouterConfig::REQUEST_POST)]
    public function saveSetting()
    {
        $inputData = $this->getRequest()->getPost();

        $data = $inputData['data'];
        $saveArr = [];
        foreach ($data as $key => $item) {
            $value = $inputData['values'][$item['field']];
            if (in_array($item['field'], Consts::ConfigArr) && !empty($value)) {
                $value = implode(',', array_filter(explode("\n", $value)));
            }
            $saveArr[] = [
                'key' => $item['field'],
                'value' => $value,
            ];
        }
        //执行保存
        Transaction::begin();
        try {
            $this->configService->saveConfig($saveArr);
            Transaction::commit();
        } catch (\Exception $exception) {
            Transaction::rollback();
            return $this->error($exception->getMessage(), '', Consts::ERR_11001);
        }

        return $this->success('保存成功');
    }

}
